package com.xiangxiao.rpan.storage.download.buffer;

import com.xiangxiao.rpan.storage.core.DownloadFileTool;
import com.xiangxiao.rpan.storage.core.DownloadFileTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @auther xiangxiao
 * @email 573768011@qq.com
 * @data 2023/12/1 17:42
 */
@Slf4j
@Component(value = "downloadFileBufferStream")
public class DownloadFileBufferStream implements DownloadFileTool {
  @Override
  public void readStreamToFile(String path, HttpServletResponse response) {
    try {
      File file = new File(path);
      String filename = file.getName();

      InputStream fis = new BufferedInputStream(new FileInputStream(path));
      byte[] buffer = new byte[fis.available()];
      fis.read(buffer);
      fis.close();

      // 清空response
      response.reset();
      // 设置response的Header
      response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
      response.addHeader("Content-Length", "" + file.length());
      OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
      response.setContentType("application/octet-stream");
      toClient.write(buffer);
      toClient.flush();
      toClient.close();
    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }

  @Override
  public String convertMuitlFileToStream(MultipartFile multipartFile, Integer chunkNumber, Integer totalChunks, long blockSize) {
    // todo
    return null;
  }
}
